#!/usr/bin/env bash
# 读小说
case $1 in
    -h|"")
        h h tts;;
    --novel|-n) # 提供一个小说文件，一段一段转为语音并播放
        shift
        echo "请稍等……"
        if [[ ! -d /tmp/tmptts/ ]]; then
            mkdir /tmp/tmptts/
        fi
        tmptxt=/tmp/tmptts/tmp$(date +%s).txt
        sed "N;N;N;N;s/\n//g;/^$/d;s/\s//g" $1 >$tmptxt
        tmpstate=0
        #mocp -S 2>/dev/null
        mocp -c 2>/dev/null
        cat $tmptxt |while read line
        do
            tmpmedia=/tmp/tmptts/tmptts$(date +%s).mp3
            edge-tts -v zh-CN-XiaoxiaoNeural -t $line --write-media $tmpmedia 2>/dev/null
            mocp -a $tmpmedia 2>/dev/null
            if [[ $tmpstate == 0 ]]; then
                mocp -p 2>/dev/null
                tmpstate=1
            fi
        done
        rm $tmptxt
        unset tmpmedia line tmpstate tmptxt ;;
    --text|-t)  # 提供一段文本，转为语音后直接播放
        shift
        edge-playback -v zh-CN-XiaoxiaoNeural -t $1;;
    --yunjian|-y)   # 提供一个文件，转为语音文件
        shift
        edge-tts --voice zh-CN-YunjianNeural --file $1 --write-media $2 ;;
    --xiaoxiao|-x)          # 提供一个文件，转为语音文件
        shift
        edge-tts -v zh-CN-XiaoxiaoNeural -f $1 --write-media $2 ;;
    *)
        echo "请稍等……"
        tmptxt=/tmp/tmp$(date +%s).txt
        if [[ -z $2 ]]; then
            cp $1 $tmptxt
        elif [[ -z $3 ]]; then
            sed -n "/^第$2章/,/^第$[$2+1]章/p" $1 >$tmptxt
        else
            sed -n "/^第$2章/,/^第$[$3+$2]章/p" $1 >$tmptxt
        fi

        tmpstring1=`sed -n "$ d;/^第.*/p" $tmptxt | sed "N;s/\n/,/g" -`
        sed -i "N;N;N;N;s/\n//g;/^$/d;s/\s//g" $tmptxt
        cat $tmptxt |while read line
        do 
            clear
            echo -e "晓晓为您朗读\e[32m“$1”\e[0m$tmpstring1。\n请稍等……"
            edge-playback -v zh-CN-XiaoxiaoNeural -t $line 1>/dev/null
        done
        rm $tmptxt
        unset tmptxt line tmpstring1;;
esac
wait
exit
